import { Component, createRef } from "react";
import { nanoid } from "nanoid";
import propTypes from "prop-types";

class AddTodo extends Component {
    constructor(props) {
        super(props);
    }
    static propTypes = {
        addTodo: propTypes.func.isRequired,
    };
    todoRef = createRef(null);
    submitTodo = (e) => {
        if (e.keyCode === 13) {
            this.addTodo();
        }
    };
    addTodo = () => {
        const value = this.todoRef.current.value;
        if (!value) {
            return false;
        }
        const todo = {
            id: nanoid(),
            content: value,
            completed: false,
        };
        this.props.addTodo(todo);
        this.todoRef.current.value = "";
    };
    render() {
        return (
            <div className='input-group'>
                <input
                    className='form-control'
                    ref={this.todoRef}
                    placeholder='请输入您的待办事项'
                    onKeyDown={this.submitTodo}
                />
                <span className='input-group-btn'>
                    <button
                        className='btn btn-danger'
                        type='button'
                        onClick={this.addTodo}
                    >
                        ADD TODO
                    </button>
                </span>
            </div>
        );
    }
}

export default AddTodo;
